package cn.ondraw.ragflow.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import cn.ondraw.common.chat.config.ChatConfig;
import cn.ondraw.common.chat.openai.OpenAiStreamClient;
import cn.ondraw.common.core.utils.OkHttpUtil;
import cn.ondraw.ragflow.pojo.ChatsAssistant;
import cn.ondraw.ragflow.pojo.RespChatsAssistant;
import cn.ondraw.ragflow.service.IRagFlowAssistantService;
import cn.ondraw.system.domain.SysModel;
import cn.ondraw.system.service.ISysModelService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
@RequiredArgsConstructor
public class RagFlowAssistantServiceImpl implements IRagFlowAssistantService {

    private final OpenAiStreamClient openAiStreamClient;
    private final ChatConfig chatConfig;
    private final ISysModelService sysModelService;

    @Override
    public List<ChatsAssistant> getChatsAssistant(String modelName) {
        // 根据模型名称获取模型信息
        SysModel sysModel = sysModelService.selectModelByName(modelName);
        // 根据模型配置创建Http客户端，向http://1.95.79.99:8038/api/v1/chats 发送请求
        OkHttpUtil okHttpUtil = new OkHttpUtil();
        okHttpUtil.setApiHost(sysModel.getApiHost());
        okHttpUtil.setApiKey("Bearer " + sysModel.getApiKey());
        Request request = okHttpUtil.createGetRequest("/api/v1/chats");
        String resJson = okHttpUtil.executeRequest(request);
        System.out.println(resJson);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            RespChatsAssistant chatsAssistant = objectMapper.readValue(resJson, RespChatsAssistant.class);
            return chatsAssistant.getData();
        } catch (Exception e) {
            log.error("Failed to parse JSON response", e);
            return new ArrayList<>();
        }
    }
}

